//
//  PresentComplexAnimator.m
//  UIViewControllerTransitionDemo
//
//  Created by Guo Rui on 2017/7/3.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "PresentComplexAnimator.h"



@implementation PresentComplexAnimator

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return .3f;
}

- (void)presentTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIViewController *toVc = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *containerView = [transitionContext containerView];
    [containerView addSubview:toVc.view];
    
    toVc.view.layer.anchorPoint = CGPointMake(1, 1);
    toVc.view.frame = CGRectOffset(toVc.view.frame, CGRectGetWidth(toVc.view.frame) / 2.f, CGRectGetHeight(toVc.view.frame) / 2.f);
    toVc.view.layer.affineTransform = CGAffineTransformMakeRotation(M_PI_2);
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        toVc.view.layer.affineTransform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        toVc.view.layer.anchorPoint = CGPointMake(.5f, .5f);
        toVc.view.frame = CGRectOffset(toVc.view.frame, -CGRectGetWidth(toVc.view.frame) / 2.f, -CGRectGetHeight(toVc.view.frame) / 2.f);
        [transitionContext completeTransition:YES];
    }];
}

- (void)dismissTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIViewController *fromVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVc   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *containerView = [transitionContext containerView];
    [containerView insertSubview:toVc.view atIndex:0];
    
    fromVc.view.layer.anchorPoint = CGPointMake(0, 1);
    fromVc.view.frame = CGRectOffset(fromVc.view.frame, -CGRectGetWidth(fromVc.view.frame) / 2.f, CGRectGetHeight(fromVc.view.frame) / 2.f);
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromVc.view.layer.affineTransform = CGAffineTransformMakeRotation(-M_PI_2);
    } completion:^(BOOL finished) {
        [fromVc.view removeFromSuperview];
        [transitionContext completeTransition:YES];
    }];
}

@end
